//
//  TipsDetailsViewController.m
//  Cooking
//
//  Created by ZhiPeng.Y on 15/8/26.
//  Copyright (c) 2015年 ZP.Y. All rights reserved.
//

#import "TipsDetailsViewController.h"
#import "AppMacro.h"
#import "TipsDetailsCollectionViewCell.h"
#import "AsyncGetConnection.h"
#import "TipsDetailsModel.h"
#import "UIImageView+WebCache.h"
#import "CookViewController.h"
#import "MBProgressHUD.h"


//记录展开按钮的点击状态
typedef NS_ENUM(NSInteger, click) {
    click_isUnSelected = 0,
    click_isSelected = 1
}myClick;


@interface TipsDetailsViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, MBProgressHUDDelegate>

@property (retain, nonatomic) UIScrollView     *detailsScroll;
@property (retain, nonatomic) UIImageView      *topImage;
@property (retain, nonatomic) UILabel          *contentLabel;
@property (retain, nonatomic) NSMutableArray   *collectionArray;
@property (retain, nonatomic) UICollectionView *recommendCollection;
@property (retain, nonatomic) UIButton         *extentButton;
@property (retain, nonatomic) MBProgressHUD    *HUD;

@end

@implementation TipsDetailsViewController

- (void)dealloc {
    [_topImage release];
    [_contentLabel release];
    [_detailsScroll release];
    [_collectionArray release];
    [_recommendCollection release];
    [_extentButton release];
    [_freshId release];
    [_HUD release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectionArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
}

#pragma mark -
#pragma mark 左侧返回键
- (void)leftButtonAction:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:255 / 255.0 green:125 / 255.0 blue:67 / 255.0 alpha:1];
    
    //左返回键
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhuianniu"] style:UIBarButtonItemStyleDone target:self action:@selector(leftButtonAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];

    
    [self createScrollView];
    [self createImageAndContentView];
    [self createRecommendCollectionView];
    [self beginConnect];
    
    
}

#pragma mark -
#pragma mark 数据请求
- (void)beginConnect {
    [AsyncGetConnection asyncGetConnectionWithURL:[NSString stringWithFormat:@"http://121.40.54.242:80/HandheldKitchen/api/found/tblFresh!getTblFreshDelicacyList.do?freshId=%@&is_traditional=0&phonetype=1", self.freshId] parameters:nil block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *array = [dic objectForKey:@"data"];
        //标题和图片赋值
        self.title = [dic objectForKey:@"title"];
        [self.topImage sd_setImageWithURL:[[array firstObject] valueForKey:@"imageFilename"]];
        _contentLabel.text = [[array firstObject] objectForKey:@"content"];
        //collectionView推荐数组
        NSArray *vegetableArray = [[array firstObject] objectForKey:@"vegetable"];
        for (NSDictionary *value in vegetableArray) {
            TipsDetailsModel *detailsModel = [[TipsDetailsModel alloc] init];
            [detailsModel setValuesForKeysWithDictionary:value];
            [_collectionArray addObject:detailsModel];
            [detailsModel release];
        }
        //自适应高度需要请求数据,获得数组长度,返回视图高度,所以在这里设置偏移量,和frame
        _recommendCollection.frame = CGRectMake(10, _contentLabel.frame.origin.y + _contentLabel.frame.size.height + 10, WIDTH - 20, (HEIGHT / 5 + 10) * _collectionArray.count / 2 + 30);
        
        _detailsScroll.contentSize = CGSizeMake(0, 10 + _topImage.frame.size.height + 10 + _contentLabel.frame.size.height + 10 + _recommendCollection.frame.size.height);
        
        [_recommendCollection reloadData];
        [_HUD hide:YES];
    }];
}

- (void)createScrollView {
    //底层scrollView
    self.detailsScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49)];
//    _detailsScroll.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:_detailsScroll];
    [_detailsScroll release];
}

- (void)createImageAndContentView {
    //顶部图片
    self.topImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, WIDTH - 20, HEIGHT / 3)];
//    _topImage.backgroundColor = [UIColor grayColor];
    _topImage.layer.cornerRadius = 5;
    _topImage.layer.masksToBounds = YES;
    [_detailsScroll addSubview:_topImage];
    [_topImage release];

    //内容
    self.contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _topImage.frame.origin.y + _topImage.frame.size.height + 10, WIDTH - 20, HEIGHT / 4)];
    _contentLabel.numberOfLines = 0;
//    _contentLabel.backgroundColor = [UIColor yellowColor];
    [_detailsScroll addSubview:_contentLabel];
    [_contentLabel release];
    
    //展开按钮
    self.extentButton = [[UIButton alloc] initWithFrame:CGRectMake(_contentLabel.frame.origin.x + _contentLabel.frame.size.width - 60, _contentLabel.frame.origin.y + _contentLabel.frame.size.height - 22, 60, 20)];
    _extentButton.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:125 / 255.0 blue:67 / 255.0 alpha:1];
    _extentButton.layer.cornerRadius = 5;
    [_extentButton setTitle:@"展开" forState:UIControlStateNormal];
    [_extentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_extentButton addTarget:self action:@selector(ententButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_detailsScroll addSubview:_extentButton];
    [_extentButton release];
    
    _extentButton.selected = click_isUnSelected;
}

- (void)createRecommendCollectionView {
    //推荐collectionView
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout alloc];
    flowLayout.itemSize = CGSizeMake((WIDTH - 20) / 2 - 5, HEIGHT / 5);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    
    self.recommendCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(10, _contentLabel.frame.origin.y + _contentLabel.frame.size.height + 10, 0, 0) collectionViewLayout:flowLayout];
    _recommendCollection.scrollEnabled = NO;
    _recommendCollection.delegate = self;
    _recommendCollection.dataSource = self;
    _recommendCollection.backgroundColor = [UIColor whiteColor];
    [_detailsScroll addSubview:_recommendCollection];
    [_recommendCollection registerClass:[TipsDetailsCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [_recommendCollection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [flowLayout release];
    [_recommendCollection release];
    
    //加载等待
    self.HUD = [[MBProgressHUD alloc] init];
    _HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
    _HUD.delegate = self;
    _HUD.backgroundColor = [UIColor clearColor];
    _HUD.detailsLabelText = @"努力加载中...";
    _HUD.dimBackground = YES;
}

#pragma mark - 
#pragma mark recommendCollection协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _collectionArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(0, 30);
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

        if (kind == UICollectionElementKindSectionHeader) {
            UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
//            header.backgroundColor = [UIColor cyanColor];
            
            //推荐星标
            UIImageView *starImage = [[UIImageView alloc] initWithFrame:CGRectMake(- 2, 4, 22, 22)];
            starImage.image = [self imageWithName:@"iconfont-tuijian" imageType:@"png"];
            [header addSubview:starImage];
            [starImage release];
            
            //推荐菜例
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, 100, 30)];
            titleLabel.text = @"推荐菜例";
            titleLabel.textColor = [UIColor colorWithRed:255 / 255.0 green:125 / 255.0 blue:67 / 255.0 alpha:1];
            //    titleLabel.backgroundColor = [UIColor grayColor];
            [header addSubview:titleLabel];
            [titleLabel release];
            return header;
       }
    return nil;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TipsDetailsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor blueColor];
    TipsDetailsModel *detailsModel = [_collectionArray objectAtIndex:indexPath.item];
    [cell sendValueWithModel:detailsModel];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CookViewController *cookVC = [[CookViewController alloc] init];
    cookVC.myID = [[_collectionArray objectAtIndex:indexPath.item] valueForKey:@"vegetable_id"];
    cookVC.nameStr = [[_collectionArray objectAtIndex:indexPath.item] valueForKey:@"name"];
    RecommendModel *recommend= [_collectionArray objectAtIndex:indexPath.item];
    cookVC.recommendModel = recommend;
    
    [self.navigationController pushViewController:cookVC animated:YES];
    [cookVC release];
}

#pragma mark-
#pragma mark 展开按钮点击事件
- (void)ententButtonAction:(id)sender {
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17.0f]};
    CGRect rect1 = [_contentLabel.text boundingRectWithSize:CGSizeMake(_contentLabel.frame.size.width, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    UIButton *button = (UIButton *)sender;
    if (button.selected == click_isUnSelected) {
        [button setTitle:@"收起" forState:UIControlStateNormal];
        CGRect rect = _contentLabel.frame;
        rect.size.height = rect1.size.height;
        _contentLabel.frame = rect;
        
        //重新设置collectionView的布局
        _recommendCollection.frame = CGRectMake(10, _contentLabel.frame.origin.y + _contentLabel.frame.size.height + 10, WIDTH - 20, (HEIGHT / 5 + 10) * _collectionArray.count / 2 + 30);
        
        //重新设置button的布局
        _extentButton.frame = CGRectMake(_contentLabel.frame.origin.x + _contentLabel.frame.size.width - 60, _contentLabel.frame.origin.y + _contentLabel.frame.size.height - 20, 60, 20);
        //重新设置scrollView的布局
        _detailsScroll.contentSize = CGSizeMake(WIDTH, 10 + _topImage.frame.size.height + 10 + _contentLabel.frame.size.height + 10 + _recommendCollection.frame.size.height);
        
    } else if (button.selected == click_isSelected) {
        [button setTitle:@"展开" forState:UIControlStateNormal];
        
        CGRect rect = _contentLabel.frame;
        rect.size.height = HEIGHT / 4;
        _contentLabel.frame = rect;
        
        //重新设置collectionView,展开按钮,scrollView的布局
        _recommendCollection.frame = CGRectMake(10, _contentLabel.frame.origin.y + _contentLabel.frame.size.height + 10, WIDTH - 20, (HEIGHT / 5 + 10) * _collectionArray.count / 2 + 30);
        
        _extentButton.frame = CGRectMake(_contentLabel.frame.origin.x + _contentLabel.frame.size.width - 60, _contentLabel.frame.origin.y + _contentLabel.frame.size.height - 20, 60, 20);
        
        _detailsScroll.contentSize = CGSizeMake(WIDTH, 10 + _topImage.frame.size.height + 10 +  _contentLabel.frame.size.height + 10 + _recommendCollection.frame.size.height);
    }
    button.selected = !button.selected;
}

#pragma mark - 
#pragma mark 获取图片
- (UIImage *)imageWithName:(NSString *)imageName imageType:(NSString *)imageType {
    NSString *path = [[NSBundle mainBundle] pathForResource:imageName ofType:imageType];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    return image;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
